<!-- eslint-disable vue/no-unused-vars -->
<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch ref="searchRef" @search="handleSearch"  @change="handleChange">
      <template #advanceBefore>
        <Button type="primary mr2" @click="handleExport" >导出</Button>
      </template>
    </CommonDateSearch>
    <div v-show="currentModel == 'table'" style="height: 100%;">
      <div class="content-box2">
        <a-tabs v-model:activeKey="currentTab" @change="changeTabData">
          <a-tab-pane v-for="item in tabData" :key="item.itemName" :tab="item.itemName"></a-tab-pane>
          <template #rightExtra>
            <!-- <a-date-picker v-model:value="year" /> -->
            <a-range-picker :getPopupContainer="(triggerNode) => triggerNode.parentNode" v-model:value="year2"
              format='YYYY-MM-DD' />
            <a-button type="primary" @click="updateList" :loading="exportLoading">同步</a-button>
          </template>
        </a-tabs>
      </div>
      <div v-if="currentTab == '特气库存用量图'">

        <Detail :chart="chart"></Detail>
      </div>
      <div v-else>
        <div class="content-box">
          <a-card class="common-card" :title="`${currentBtn}的数据`">
            <!-- <template #extra>
              <a-space>

                <DatePicker v-model:value="dateMonthValue" picker="month"> </DatePicker>
                <a-button type="primary">导出</a-button>
                <a-button type="primary">新增</a-button>
              </a-space>
            </template> -->
            <BasicTable @register="registerTable">


              <template #bodyCell="{ column, record }">

                <template v-if="column.key === 'action'">
                  <TableAction :actions="createActions(record)" />
                </template>
              </template>
            </BasicTable>
          </a-card>
        </div>
      </div>
    </div>

    <!-- <div class="content-box">
      <a-card class="common-card flex table-box">
        <TotalTable ref="totalTableRef" :loading="loadingTotalTableRef"></TotalTable>
      </a-card>
    </div> -->
    <div v-show="currentModel != 'table'" class="main-box" style="height: 100%">
      <speciaGasCharts ref="csssGasChartsRef"></speciaGasCharts>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>

import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { PageWrapper } from '@/components/Page'
import CommonDateSearch from './CommonDateSearch.vue'
import Icon from '@/components/Icon/Icon.vue'
import { BasicTable, useTable, TableAction } from '@/components/Table'
import { cloneDeep, head } from 'lodash-es'
import TotalTable from './totalTable.vue'
import { Button } from 'ant-design-vue';
import { getSelectTgmData, postTgmConsumptionAddOrUpdate, exportTgmData } from '@/api/common/chart'
import {
  getTgmplanNumDataSyn
} from '@/api/power/airConditioning/dailyUsage'
import { getDictListByCode } from '@/api/sys/dict'
import dayjs, { Dayjs } from 'dayjs'
import { useMessage } from '@/hooks/web/useMessage'
import Detail from './Detail.vue'
import speciaGasCharts from './speciaGasCharts.vue';
import {
    downloadByData,
  } from '@/utils/file/download';
const currentModel = ref('table')
const csssGasChartsRef = ref(null)
const chart = 'gas_tgm_consumption_chart'
const tabData = ref()
const currentTab = ref()
const dateList = reactive([])
const currentEditKeyRef = ref('')
const dateMonthValue = ref(dayjs())
const currentBtn = ref('CVD')
const classifyId = ref('')
const year2 = ref<dayjs[]>([dayjs(), dayjs()])
const exportLoading = ref(false)
const searchRef = ref()
const searchInfo = reactive({})

const { createMessage: msg } = useMessage();
const dictCode = 'gas_tgm_consumption'
const classifyIdsObj:any = ref({
  classifyIds:[],
})



const [registerTable, { reload, setLoading, setColumns, setTableData }] = useTable({
  rowKey: 'id',
  columns: [],
  pagination: false,
  formConfig: {
    labelWidth: 120,
  },
  bordered: true,
  striped: true,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
  },
  // showSummary: true,
})
const handleExport = async () => {
  const { data, headers } = await exportTgmData({...searchInfo})
  let contentDisposition = decodeURIComponent(headers["content-disposition"])
  const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
  const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]
  downloadByData(data, fileName)
}
const handleChange = (val) => {
  console.log(val)
  currentModel.value = val
}
function createActions(record) {


  if (!record.editable) {
    return [
      {
        label: '编辑',
        disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.id : false,
        onClick: handleEdit.bind(null, record),
      },

    ]
  }
  return [
    {
      label: '保存',
      onClick: handleSave.bind(null, record),
    },
    {
      label: '取消',
      onClick: handleCancel.bind(null, record),
    },
  ]
}
const updateList = () => {
  const [startTime, endTime] = year2.value;
  const formattedStart = startTime.format('YYYY-MM-DD'); // 格式化为 'YYYY-MM-DD'
  const formattedEnd = endTime.format('YYYY-MM-DD');
  // exportLoading.value = true
  console.log(formattedStart, formattedEnd);
  getTgmplanNumDataSyn({ startDate: formattedStart, endDate: formattedEnd, planNum: "" })
}
const handleCancel = (record) => {
  currentEditKeyRef.value = ''
  record.onEdit?.(false, false)
}

const handleEdit = (record) => {


  currentEditKeyRef.value = record.key
  record.onEdit?.(true)


}
const handleSave = async (record) => {
  // console.log(record, dateList.value);

  // 校验
  currentEditKeyRef.value = ''
  // record.onEdit?.(false, false)
  const valid = await record.onValid?.()
  console.log(valid);

  // if (valid) {
  // const editData = cloneDeep(record.editValueRefs)


  const deviceCustomDataValDTOList = dateList.value
    .map((dateStr, index) => {
      const key = String(index);
      const exists = record.hasOwnProperty(key);
      const value = exists ? record[key] : 0;
      console.log(`Processing index ${index}:`, { dateStr, key, exists, value });

      return value !== 0 ? { date: dateStr, dailyConsumption: value, remark: '' } : null;
    })
    .filter(item => item !== null);
  const remarkValue = record.remark || '';

  // 将 remark 字段添加到最后一个对象中
  if (deviceCustomDataValDTOList.length > 0) {
    deviceCustomDataValDTOList[deviceCustomDataValDTOList.length - 1].remark = remarkValue;
  }

  if (deviceCustomDataValDTOList.length > 0) {
    const lastIndex = deviceCustomDataValDTOList.length - 1;
    deviceCustomDataValDTOList[lastIndex].remark = remarkValue;
    // 将 totalStock 字段添加到最后一个对象，值为最后一个 dailyConsumption 的值
    deviceCustomDataValDTOList[lastIndex].totalStock = deviceCustomDataValDTOList[lastIndex].dailyConsumption;
  }

  const data = {
    classifyId: record.type,
    data: deviceCustomDataValDTOList,
  }
  console.log(data, "asd");
  await postTgmConsumptionAddOrUpdate(data)
  const pass = await record.onEdit?.(false, true)
  // if (pass) {
  //   currentEditKeyRef.value = ''
  // }
  msg.success({ content: '数据已保存', key: 'saving' })
  handleCancel(record)
  getTypeList()
  // reload()
  // }
  // else {
  //   msg.error({ content: '请填写正确的数据', key: 'saving' })
  // }
}
const formatEditedData = (editedData, deviceCustomDataVal) => {
  console.log(editedData, deviceCustomDataVal);

  const rowData = cloneDeep(deviceCustomDataVal)
  for (const key in editedData) {
    const [, subKey, field] = key.split(',')

    if (rowData[subKey]) {
      // 编辑的单元格没有值，为null
      if (editedData[key] === null) {
        // 如果原来有值，但是删掉了，要置成0，根据有measureTime判断原来有值
        if (rowData[subKey].measureTime) {
          rowData[subKey][field] = 0
        } else {
          delete rowData[subKey]
        }
      } else {
        // 确保每一条有效数据都有measureTime
        rowData[subKey] = {
          ...rowData[subKey],
          [field]: editedData[key],
          measureTime: subKey,
        }
      }
    }
  }

  return Object.values(rowData)
}

onMounted(async () => {
  searchRef.value.handleSearch()
  getTypeList()
  // 
  // getTotalData()
})
const handleSearch = (params) => {
  console.log(params);
  Object.assign(searchInfo, params)
  if (currentModel.value == 'table') {
    getData()
  } else {
    csssGasChartsRef.value.getData(searchInfo, classifyIdsObj.value.classifyIds)
  }
}
watch(
  () => dateMonthValue.value,
  (readyVal) => {
    getData()

    // getTotalData()
  },
)

const formatHeader = (headerData) => {
  dateList.value = headerData
  const headerList = [
    {
      title: '气体名称',
      dataIndex: 'gasName',
      width: 120,
      fixed: 'left',
      // merge: true,
    },
    {
      title: '物料号',
      dataIndex: 'materialNumber',
      width: 120,
      fixed: 'left',
      // merge: true,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: 60,
      fixed: 'left',
      merge: true,
    },
    {
      title: '目前总库存量',
      dataIndex: 'totalStock',
      width: 120,
      fixed: 'right',
      merge: true,
    },

  ]

  headerData.forEach((item, index) => {
    headerList.push({
      title: `${dayjs(item).format('MM/DD')}`,
      dataIndex: index.toString(),
      width: 100,
      editRow: true,

      customRender: ({ text }) => {
        // return "123"
        if (typeof text === 'number') {
          return text
        } else {
          return text || '--'
        }
      },
    })
  })


  headerList.push({
    title: '最近7天平均使用量',
    dataIndex: 'recentSevenDaysAverage',
    width: 120,
    customRender: ({ record }) => {
      const lastSevenDaysData = [];
      const startIndex = Math.max(0, dateList.value.length - 7);
      for (let i = startIndex; i < dateList.value.length; i++) {
        let value = record[i];
        if (value === null) {
          value = 0;
        }
        if (typeof value === 'string') {
          const numValue = parseFloat(value);
          if (!isNaN(numValue)) {
            lastSevenDaysData.push(numValue);
          }
        } else if (typeof value === 'number') {
          lastSevenDaysData.push(value);
        }
      }
      const sum = lastSevenDaysData.reduce((acc, val) => acc + val, 0);
      const average = sum / lastSevenDaysData.length;
      return isNaN(average) ? '--' : average.toFixed(4);
    }



  },
    {
      title: '需要补充库存',
      dataIndex: 'remark',
      width: 120,
      // fixed: 'right',
      merge: true,
      editRow: true,
    })
  console.log(headerData);

  setColumns(headerList)
}

const formatTableData = (tableData) => {
  console.log(tableData);

  const data = tableData.map((item) => {
    const { data: itemData, ...others } = item;
    const record = reactive({ ...others });
    itemData.forEach((value, index) => {
      record[index] = value;
    });
    return record;
  });


  setTableData(data)
}
const changeTabData = (itemName) => {
  let itemCode
  tabData.value.forEach((item) => {
    // item, itemName
    if (item.itemName == itemName) {
      itemCode = item.itemCode
    }
  }
  );
  currentTab.value = itemName

  if (currentTab.value != '特气库存用量图') {
    currentBtn.value = currentTab.value
    classifyId.value = itemCode
    getData()

  }
  console.log(itemName);

}
const getTypeList = async () => {
  const res = await getDictListByCode(dictCode)
  console.log(res, 'electrical_science_classification_of_each_department');


  tabData.value = [
    ...res, // 后端返回的 Tab 数据
    // { itemCode: chart, itemName: '特气库存用量图' } // 新增的写死 Tab
  ];
  classifyId.value = res[0].itemCode
  // commonConfig.dictCodeInfo = res
  // getSubItem(res, false)
  classifyIdsObj.value.classifyIds = res
  getData()
}



const getData = () => {
  setLoading(true)
  if (classifyId.value) {
    getSelectTgmData({
      startDay: searchInfo.startDay,
      endDay: searchInfo.endDay,
      queryType: searchInfo.queryType,
      classifyId: classifyId.value,
      // queryType: 'month',
      // startDay: dateMonthValue.value.format('YYYY-MM'),

    })
      .then((e) => {
        formatHeader(e.xaxisList)
        formatTableData(e.yaxisList)
      })
      .catch((e) => {
        console.log('分项数据报错', e)
      })
      .finally(() => {
        setLoading(false)
      })
  }

}

watch(() => [classifyIdsObj.value, currentModel.value], (val) => {
  console.log(val, 3333)
  if (val[0].classifyIds.length && val[1] == 'chart') {
    nextTick(() => {
      csssGasChartsRef.value.getData(searchInfo, val[0].classifyIds)
    })
  }
},{
  deep: true
})
</script>
<style scoped lang="scss">
.subitem-box {

  //分项按钮的样式-开始
  .subitem-btn {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(208 212 223 / 100%);
    border-radius: 2px;
    background: #f3f7fb;
    box-shadow: none;
    color: #181818;
    font-size: 12px;
    font-weight: 400;
  }

  .subitem-btn-focus {
    width: 112px;
    height: 28px;
    border: 1px solid rgb(0 103 204 / 100%);
    border-radius: 2px;
    background: rgb(0 103 204 / 15%);
    box-shadow: none;
    color: #0067cc;
  }

  .ant-space {
    margin-bottom: 0 !important;
  }

  //分项按钮的样式-结束
}

.content-box2 {
  display: flex;

  flex-direction: column;
  padding: 0 8px;
  background: #fff;
}

.content-box {
  display: flex;
  flex: 1;
  flex-direction: column;

  background: #fff;

  :deep(.ant-table-body) {
    height: 100% !important;
  }

  .table-box {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
  }

  :deep(.ant-table-wrapper) {
    padding: 0;
  }
}
</style>
